﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using Sunboxsoft.WinForm;
using Sunboxsoft.Common;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors;
using System.Text.RegularExpressions;
using WebRef = Sunboxsoft.ASMS.Client.Domain.WebRef;
using BasesWebRef = Sunboxsoft.ASMS.Client.Domain.BasesWebRef;
using Service = Sunboxsoft.ASMS.Client.Domain.Service;
using LocalService = Sunboxsoft.ASMS.Client.Domain.LocalService;
using Sunboxsoft.ASMS.Client.UI.Properties;
namespace Sunboxsoft.ASMS.Client.UI.Create
{
    /// <summary>
    /// 新增客户
    /// </summary>
    public partial class CreateCustomerView : UserControl, IView
    {
        Promise _promise = new Promise();
        Common.Validations.TextEditIdNumberValidation _idNumberValidation = null;
        Common.Validations.LookUpEditValidation _lookUpEditValidation = null;
        public CreateCustomerView()
        {
            InitializeComponent();
            ValidationManager.Register(this, new Common.Validations.TextEditTelephoneValidation(ctlEditTelephone, false));
            _idNumberValidation = new Common.Validations.TextEditIdNumberValidation(ctlEditIdNumber, true);
            ValidationManager.Register(this, _idNumberValidation);
            ValidationManager.Register(this, new Common.Validations.TextEditEMailValidation(txtEMail));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditName, "姓名", false));
            ValidationManager.Register(this, new Common.Validations.SearchLookUpEditValidation(ctlSelectLookUpEditCustomerType, "客户类型"));
            _lookUpEditValidation = new Common.Validations.LookUpEditValidation(this.ctlLookUpGenders, "性别");
            ValidationManager.Register(this, _lookUpEditValidation);
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(ctlEditAddress, "详细地址", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNumberValidation(txtQQ, "QQ号码", true));
            ValidationManager.Register(this, new Common.Validations.TextEditIsNotNullValidation(txtWebChat, "微信号码", true));
        }

        #region Method
        /// <summary>
        /// 创建客户
        /// </summary>
        private void CreateCustomer()
        {
            WebRef.ECustomer model = new WebRef.ECustomer();
            model.Name = this.ctlEditName.EditValue.ToString();
            model.Telephone = this.ctlEditTelephone.EditValue.ToString();
            model.EMail = this.txtEMail.Text.Trim();
            if (this.ctlEditIdNumber.EditValue != null)
            {
                model.IdNumber = this.ctlEditIdNumber.EditValue.ToString();
            }
            model.Country = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCountry).GetCode();
            model.Province = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpProvince).GetCode();
            model.City = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCity).GetCode();
            model.District = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpDistrict).GetCode();
            model.Address = this.ctlEditAddress.Text.Trim();
            model.Type = SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlSelectLookUpEditCustomerType).GetCode(); ;
            model.QQ = this.txtQQ.EditValue == null ? null : this.txtQQ.EditValue.ToString();
            model.Wechat = this.txtWebChat.EditValue == null ? null : this.txtWebChat.EditValue.ToString();
            model.VIPNumber = this.ctlEditVIPNumber.EditValue == null ? null : this.ctlEditVIPNumber.EditValue.ToString();
            model.VIPLevelCode = this.ctlEditVIPLevel.Tag == null ? null : this.ctlEditVIPLevel.Tag.ToString();
            if (LookUpEditUtil.GetSelectObject<Domain.IntCodeTextItem>(this.ctlLookUpGenders) != null)
            {
                model.Gender = LookUpEditUtil.GetSelectObject<Domain.IntCodeTextItem>(this.ctlLookUpGenders).Code;
            }
            if (this.ctlDateBirthday.EditValue != null)
            {
                model.Birthday = Convert.ToDateTime(this.ctlDateBirthday.EditValue);
            }
            model.IsCredit = ctlListIsOnTrust.EditValue.ToString().Equals("是") ? true : false;
            WebRef.VStaffPosition vStaffPosition = SearchLookUpEditUtil.GetSelectedValue<WebRef.VStaffPosition>(this.ctlSearchLookUpEditSalesManager);
            if (vStaffPosition != null)
            {
                model.SalesManagerId = vStaffPosition.StaffId;
            }
            this.ShowMask("loading...");
            UIContext.Current.InvokeAsync(() =>
            {
                SingleResult<WebRef.ECustomer> result = new Service.CreateService().CreateCustomer(model);
                this.BeginInvoke(new Action(() =>
                {
                    this.HideMask();
                    if (result.IsSuccess)
                    {
                        UIContext.Current.ViewManager.CloseView(true, result.Data);
                        _promise.Resolve();
                    }
                    else
                    {
                        UIContext.Current.ViewManager.ShowError(result.Message);
                        _promise.Reject();
                    }
                }));
            });
        }

        #endregion

        #region IView 成员

        public void RegisterAction(ActionNodeCollection collection)
        {
            if (UIContext.Current.ViewContext.Stack.HasAnyBackground())
            {
                // 在当前视图后面还存在别的视图,显示取消按钮
                collection.AddAction(new ActionNode("reset", Resources.isReset, "重置", ctlBtnResetClick))
                    .AddAction(new ActionNode("save", Resources.isOK, "保存", ctlBtnSave_Click))
                    .AddAction(new ActionNode("cancel", Resources.isDelete, "取消", ctlBtnCancel_Click));
            }
            else
            {
                collection.AddAction("reset", "重置", ctlBtnResetClick)
                    .AddAction(new ActionNode("save", Resources.isOK, "保存", ctlBtnSave_Click));
            }
        }

        public void Resume(ViewResumeArgs args)
        {
        }

        public void Active(ViewActiveArgs args)
        {
            LookUpEditUtil.BindIntCodeTextItem(this.ctlLookUpGenders, Domain.Constant.Genders.Enumerate(), null, true);
            _promise.Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(this.ctlSelectLookUpEditCustomerType, _promise, Domain.Constant.MasterDataCodes.CustumerType);
            })
            .Then(() =>
                {
                    SearchLookUpEditUtil.BindVStaffPosition(this.ctlSearchLookUpEditSalesManager, _promise, Domain.Constant.StaffPosts.SalesManager);
                }
            ).Then(() =>
            {
                SearchLookUpEditUtil.BindEMasterDataItem(ctlLookUpCountry, _promise, Domain.Constant.MasterDataCodes.Country,
                    null, null, true, true);
            }).Run(null);
        }
        public ViewHeader GetHeader()
        {
            return new ViewHeader("新增客户");
        }
        #endregion

        #region Action
        void ctlBtnResetClick(object sender, object e)
        {
            if (!string.IsNullOrEmpty(ctlEditTelephone.Text))
            {
                if (!UIContext.Current.ViewManager.ShowQuestion("是否重置，重新输入客户信息?"))
                {
                    return;
                }
            }
            ctlEditTelephone.EditValue = null;
            ctlEditName.EditValue = null;
            ctlEditIdNumber.EditValue = null;
            txtEMail.EditValue = null;
            ctlDateBirthday.EditValue = null;
            ctlEditVIPNumber.EditValue = null;
            ctlEditVIPNumber.Tag = null;
            ctlEditVIPLevel.EditValue = null;
            ctlEditVIPLevel.Tag = null;

            ctlEditTelephone.Enabled = true;
            ctlEditName.Enabled = true;
            ctlEditIdNumber.Enabled = true;
            txtEMail.Enabled = true;
            ctlDateBirthday.Enabled = true;

            ctlEditTelephone.Focus();
        }
        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnSave_Click(object sender, object e)
        {
            string message = null;
            if (ValidationManager.Validate(this, out message))
            {
                CreateCustomer();
            }
            else
            {
                UIContext.Current.ViewManager.ShowError(message);
            }
        }
        /// <summary>
        /// 取消
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlBtnCancel_Click(object sender, object e)
        {
            UIContext.Current.ViewManager.CloseView(false, null);
        }
        /// <summary>
        /// 根据选择国家获取省份
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupCountry_EditValueChanged(object sender, EventArgs e)
        {
            SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpProvince, _promise,
                Domain.Constant.MasterDataCodes.Province,
                SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCountry).GetCode(),
                null,
                true, true);
        }
        /// <summary>
        /// 根据选择省获取市
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupProvince_EditValueChanged(object sender, EventArgs e)
        {
            SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpCity, _promise,
                Domain.Constant.MasterDataCodes.City,
                 SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpProvince).GetCode(),
                 null, true, true);
        }
        /// <summary>
        /// 根据市获取区
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void lupCity_EditValueChanged(object sender, EventArgs e)
        {
            if (this.ctlLookUpCity.EditValue == null)
                return;

            SearchLookUpEditUtil.BindEMasterDataItem(this.ctlLookUpDistrict, _promise,
                Domain.Constant.MasterDataCodes.District,
                SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlLookUpCity).GetCode(), null, true, true);
        }
        private void ctlBtnCheck_Click(object sender, EventArgs e)
        {
            string telephone = ctlEditTelephone.Text.Trim();
            if (!string.IsNullOrEmpty(telephone))
            {
                this.ShowMask();
                UIContext.Current.InvokeAsync(() =>
                {
                    SingleResult<BasesWebRef.VIPCustomer> result = new Service.CheckService().CheckVIP(telephone);
                    this.BeginInvoke(new Action(() =>
                    {
                        if (result.IsSuccess)
                        {
                            ctlEditTelephone.Enabled = false;
                            ctlEditName.Enabled = false;
                            txtEMail.Enabled = false;
                            ctlDateBirthday.Enabled = false;

                            ctlEditVIPNumber.Text = result.Data.VIPNumber;
                            ctlEditVIPLevel.Text = result.Data.GradeName;
                            ctlEditVIPLevel.Tag = result.Data.GradeCode;
                            ctlEditName.Text = result.Data.Name;
                            if (string.IsNullOrEmpty(result.Data.IdNumber))
                            {
                                ctlEditIdNumber.Text = null;
                                ctlEditIdNumber.Enabled = true;
                            }
                            else
                            {
                                ctlEditIdNumber.Text = result.Data.IdNumber;
                                ctlEditIdNumber.Enabled = false;
                            }

                            if (string.IsNullOrEmpty(result.Data.EMail))
                            {
                                txtEMail.Text = null;
                                txtEMail.Enabled = true;
                            }
                            else
                            {
                                txtEMail.Text = result.Data.EMail;
                                txtEMail.Enabled = false;
                            }

                            if (null == result.Data.BirthDay)
                            {
                                ctlDateBirthday.EditValue = null;
                                ctlDateBirthday.Enabled = true;
                            }
                            else
                            {
                                ctlDateBirthday.DateTime = result.Data.BirthDay.Value;
                                ctlDateBirthday.Enabled = false;
                            }
                        }
                        else
                        {
                            ctlEditName.Enabled = true;
                            ctlEditIdNumber.Enabled = true;
                            txtEMail.Enabled = true;
                            ctlDateBirthday.Enabled = true;
                        }
                        this.HideMask();
                    }));
                });
            }
        }
        /// <summary>
        /// 客户类型为公司时不验证身份证号码
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void ctlSelectLookUpEditCustomerType_EditValueChanged(object sender, EventArgs e)
        {
            if (SearchLookUpEditUtil.GetSelectedValue<WebRef.EMasterDataItem>(this.ctlSelectLookUpEditCustomerType).GetCode() != "CT0002")
            {
                ValidationManager.Register(this, _idNumberValidation);
                ValidationManager.Register(this, _lookUpEditValidation);
                ctllblGenderFlag.Visible = true;
            }
            else
            {
                ValidationManager.Unregister(this, _idNumberValidation);
                ValidationManager.Unregister(this, _lookUpEditValidation);
                ctllblGenderFlag.Visible = false;
            }
        }
        #endregion
    }
}
